package com.yueyang.sojourn.server.validation;

import com.yueyang.sojourn.server.model.enums.IEnum;
import com.yueyang.sojourn.server.validation.annotation.EnumValid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yemingxing
 * @summary 枚举值 参数校验器
 * @Copyright (c) 2020, Yueyang Group All Rights Reserved.
 * @since 2020-02-15 15:26
 */
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {

    private EnumValid annotation;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        IEnum[] iEnums = annotation.clazz().getEnumConstants();
        List<Integer> enumCodes = Arrays.stream(iEnums).map(IEnum::getCode).collect(Collectors.toList());
        if (value instanceof List) {
            return enumCodes.containsAll((List) value);
        }else {
            return enumCodes.contains(value);
        }
    }
}
